package com.ljs.threadpooldemo.service;

import cn.hutool.core.date.DateUtil;
import com.ljs.threadpooldemo.service.run.RunnableA;
import com.ljs.threadpooldemo.service.run.RunnableB;
import com.ljs.threadpooldemo.service.run.RunnableC;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestExecutorService {
      /** Executors.newCachedThreadPool 创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程。
       Executors.newFixedThreadPool 创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。
       Executors.newScheduledThreadPool 创建一个定长线程池，支持定时及周期性任务执行。
       Executors.newSingleThreadExecutor 创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
       备注：Executors只是一个工厂类，它所有的方法返回的都是ThreadPoolExecutor、ScheduledThreadPoolExecutor这两个类的实例。
       **/
    public static   ExecutorService executorService1= Executors.newFixedThreadPool(3);
    public static   ExecutorService executorService2= Executors.newFixedThreadPool(3);
    public static   ExecutorService executorService3= Executors.newFixedThreadPool(3);
    public static   ExecutorService executorService4= Executors.newFixedThreadPool(3);



    public static void main(String[] args) throws ExecutionException, InterruptedException {
        RunnableA runnableA=new RunnableA();
        //submit方法会有返回值，可以通过返回null说明执行完毕了
        Future future=  executorService1.submit(runnableA);
        executorService1.submit(()->{
            System.out.println("lambda表达式执行");
            System.out.println("当前线程开始执行"+Thread.currentThread().getId());
            for (int i=0;i<10000;i++){
                System.out.println(i);
            }
            System.out.println("我做A的事,时间"+ DateUtil.now());
            System.out.println("当前线程结束执行"+Thread.currentThread().getId());
        });
        System.out.println( future.get());
        System.out.println( future.get());//如果返回null,说明执行完成了
        RunnableB runnableB=new RunnableB();
        Future future2=  executorService2.submit(runnableB);
        System.out.println( future2.get());//如果返回null,说明执行完成了

        RunnableC runnableC=new RunnableC();
        Future future3=  executorService3.submit(runnableC);
        System.out.println( future3.get());
        //这个是没有返回值的
        executorService4.execute(runnableC);

    }
}
